package com.robot.orders.dao;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import com.robot.orders.pojo.Purchase;
import org.springframework.data.jpa.repository.Query;

import java.math.BigDecimal;
import java.util.List;

/**
 * purchase数据访问接口
 *
 * @author lin
 */
public interface PurchaseDao extends JpaRepository<Purchase, String>, JpaSpecificationExecutor<Purchase> {
    /**
     * 通过agentId查询purchase列表并分页
     *
     * @param agentId
     * @param pageable
     * @return
     */
    public Page<Purchase> findAllByAgentIdAndDeletedAtIsNullOrderByCreatedAtDesc(String agentId, Pageable pageable);

    /**
     * 通过agentId和status查询purchase列表并分页
     *
     * @param agentId
     * @param status
     * @param pageable
     * @return
     */
    public Page<Purchase> findAllByAgentIdAndStatusAndDeletedAtIsNullOrderByCreatedAtDesc(String agentId, String status, Pageable pageable);

    /**
     * 通过agentId,storeId,status查询purchase列表,按createdAt正序输出
     *
     * @param agentId
     * @param storeId
     * @param status
     * @return
     */
    public List<Purchase> findAllByAgentIdAndStoreIdAndStatusOrderByCreatedAt(String agentId, String storeId, String status);

    /**
     * 通过agentId和id查询purchase详情
     *
     * @param id
     * @param agentId
     * @return
     */
    public Purchase findByIdAndAgentId(String id, String agentId);

    /**
     * 通过agentId和storeId查找余额
     *
     * @param agentId
     * @param storeId
     * @return
     */
    @Query(value = "select sum(balance) from orders.purchase where agent_id=? and store_id=? and status=0 or status=1", nativeQuery = true)
    public BigDecimal findPurchaseBalanceByAgentIdAndStoreId(String agentId, String storeId);


    /**
     * 通过storeId查询purchase列表并分页
     *
     * @param storeId
     * @param pageable
     * @return
     */
    public Page<Purchase> findAllByStoreIdAndDeletedAtIsNullOrderByCreatedAtDesc(String storeId, Pageable pageable);

    /**
     * 通过storeId和status查询purchase列表并分页
     *
     * @param storeId
     * @param status
     * @param pageable
     * @return
     */
    public Page<Purchase> findAllByStoreIdAndStatusAndDeletedAtIsNullOrderByCreatedAtDesc(String storeId, String status, Pageable pageable);

    /**
     * 通过storeId和id查询purchase详情
     *
     * @param id
     * @param storeId
     * @return
     */
    public Purchase findByIdAndStoreId(String id, String storeId);

    /**
     * 根据storeId查找剩余余额
     *
     * @param storeId
     * @return
     */
    @Query(value = "select sum(balance) from orders.purchase where store_id=? and status=0 or status=1", nativeQuery = true)
    public String findBalanceByStoreId(String storeId);
}
